import { defineStore } from 'pinia'
import axios from 'axios'
import router from '@/router'
import { clearAuth } from '@/utils/auth'

// 创建 axios 实例
const request = axios.create({
  baseURL: '/api',
  timeout: 5000
})

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null')
  }),
  
  actions: {
    // 登录
    async login(loginForm) {
      try {
        const response = await request.post('/v1/medical/user/login', loginForm)
        if (response.data.code === '0000') {
          const { token, type } = response.data.data
          console.log('登录用户类型:', type, '类型:', typeof type)
          
          this.token = token
          this.userInfo = { type }
          
          localStorage.setItem('token', token)
          localStorage.setItem('userType', type)
          localStorage.setItem('userInfo', JSON.stringify({ type }))
          
          // 根据用户类型跳转到不同页面
          if (type === '1' || type === 1) {
            console.log('检测到管理员用户，准备跳转到管理后台')
            // 管理员跳转到管理后台
            router.push('/admin')
          } else {
            console.log('检测到普通用户，准备跳转到首页')
            // 普通用户跳转到首页
            router.push('/home')
          }
          return true
        }
        return false
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },
    
    // 注册
    async register(userInfo) {
      try {
        const response = await request.post('/v1/medical/user/register', userInfo)
        return response.data.code === '0000'
      } catch (error) {
        console.error('注册失败:', error)
        return false
      }
    },
    
    // 退出登录
    logout() {
      this.token = null
      this.userInfo = null
      clearAuth()
      router.push('/login')
    },

    // 从本地存储恢复状态
    restoreState() {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')
      
      if (token) {
        this.token = token
      }
      
      if (userInfo) {
        try {
          this.userInfo = JSON.parse(userInfo)
        } catch (e) {
          console.error('解析用户信息失败:', e)
          this.userInfo = null
        }
      }
    }
  },

  getters: {
    isLoggedIn: (state) => !!state.token,
    getToken: (state) => state.token,
    getUserInfo: (state) => state.userInfo
  }
}) 